<?php

namespace app\common\model;

use think\Env;
use think\Model;
use EasyWeChat\Factory;

/**
 * 小程序配置
 */
class MiniApp extends Model
{
    protected $config;

    public function initialize()
    {
        parent::initialize();
        $this->config = [
            'app_id' => Env::get('wxconfig.app_id', ''),
            'secret' => Env::get('wxconfig.secret', ''),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
    }

    //获取小程序配置
    public function getMiniAppConfig()
    {
        return $this->config;
    }

    //获取小程序码
    public function getMiniAppQrcode($uid, $page, $carId = null, $width = 600)
    {

        // done：数据库取数据or生成二维码
        $where['user_id'] = $uid;
        $where['page'] = $page;
        $where['width'] = $width;

        //生成小程序码
        $scene    = $carId ? "uid={$uid},car_id={$carId}" : "uid={$uid}";
        $optional = [
            'page'  => $page,
            'width' => $width,
        ];
        $app = Factory::miniProgram($this->config);
        $response = $app->app_code->getUnlimit($scene, $optional);
        $filename = md5($uid) . '.png';

        if (is_object($response)) {
            $path = 'qrcode';
            $filename = $response->save($path, $filename);
            return cdnurl('/' . $path . '/' . $filename, true);

            //TODO:保存小程序码图片到七牛云
            // $contents = $response->getBody()->getCon tents();
            // if (empty($contents) || '{' === $contents[0]) {
            //     throw new RuntimeException('Invalid media response content.');
            // }
            // $res = Qiniu::upload_base64(1,$contents);
            // return $res;
        }
        return '';
    }
}
